import { REFRESH_TO_LOGIN_PAGE_MSG, STORAGE_KEY_USER_INFU } from '@/consts/consts'
import { refreshToLoginPage } from '@/utils/utils'
import type { IUserInfo } from '.'

export const getUserInfo = (json?: string): IUserInfo | null => {
  try {
    return JSON.parse(json ?? localStorage.getItem(STORAGE_KEY_USER_INFU) ?? '')
  } catch {
    return null
  }
}

export const apiGetUserInfo = async (): Promise<IUserInfo> => {
  return new Promise((resolve, reject) => {
    const data = getUserInfo()
    if (data) {
      resolve(data)
    } else {
      refreshToLoginPage()
      reject(new Error(REFRESH_TO_LOGIN_PAGE_MSG))
    }
  })
}
